package com.bsj.pay.service.impl;

import com.bsj.pay.config.GlobalConfig;
import com.bsj.pay.dao.AccountDao;
import com.bsj.pay.model.AccountBean;
import com.bsj.pay.model.IpPoolBean;
import com.bsj.pay.service.AccountService;
import com.bsj.pay.service.IpPoolService;
import com.bsj.pay.util.SpringUtil;
import com.bsj.pay.util.ThreadPoolUtils;
import com.bsj.pay.util.platform.PlatformInterface;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class AccountServiceImpl implements AccountService {

    private static final Logger logger = LogManager.getLogger(AccountServiceImpl.class);

    @Autowired
    private AccountDao dao;

    @Autowired
    private IpPoolService ipPoolService;

    @Override
    public long insert(AccountBean t) {
        // TODO Auto-generated method stub
        return dao.insert(t);
    }

    @Override
    public int deleteById(Long id) {
        // TODO Auto-generated method stub
        return dao.deleteById(id);
    }

    @Override
    public List<AccountBean> queryList(AccountBean t) {
        // TODO Auto-generated method stub
        return dao.queryList(t);
    }

    @Override
    public int update(AccountBean t) {
        // TODO Auto-generated method stub
        return dao.update(t);
    }

    @Override
    public AccountBean getById(Long Id) {
        // TODO Auto-generated method stub
        return dao.getById(Id);
    }

    @Override
    public long count(AccountBean t) {
        // TODO Auto-generated method stub
        return dao.count(t);
    }

    @Override
    public PageInfo<AccountBean> pageList(AccountBean t, int pageNum, int pageSize) {
        // TODO Auto-generated method stub
        PageHelper.startPage(pageNum, pageSize);
        List<AccountBean> list = dao.adminQueryList(t);
        PageInfo<AccountBean> pageInfo = new PageInfo<AccountBean>(list);
        return pageInfo;
    }

    @Override
    public int removeById(Long id) {
        // TODO Auto-generated method stub
        return dao.removeById(id);
    }

    @Override
    public List<AccountBean> queryAll() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void accountOnlineTask() throws Exception {
        // TODO Auto-generated method stub
        List<AccountBean> list = dao.getNeedCheckOnlieList();
        if (list == null || list.size() == 0) return;
        for (AccountBean account : list) {
            if (StringUtils.isEmpty(account.getLogin_cookie()) && StringUtils.isEmpty(account.getPassword())) continue;
            ThreadPoolUtils.getAccountOnlinePool().execute(() -> {
                try {
                    PlatformInterface inf = (PlatformInterface) SpringUtil.getBean(account.getOperator() + "Util");
                    inf.online(account);
                    logger.info("保持登录在线,账号:{}，登录状态正常", account.getAccount());
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.info("保持登录在线异常,账号:{},{}", account.getAccount(), e.getMessage());
                    if (e.getMessage() != null && e.getMessage().contains("网络链接失败")) {
                        dao.addProxyFailTimes(account.getId());
                    } else {
                        AccountBean updateModel = new AccountBean();
                        updateModel.setId(account.getId());
                        updateModel.setLogin_status(2);
                        if (!"weidian".equalsIgnoreCase(account.getOperator())) {
                            updateModel.setLogin_cookie("");
                        }
                        updateModel.setUpdate_time(System.currentTimeMillis() / 1000);
                        updateModel.setRemarks(e.getMessage());
                        dao.update(updateModel);
                    }
                }
            });
        }
        do {
            Thread.sleep(1000);
        } while (ThreadPoolUtils.getAccountOnlinePool().getActiveCount() != 0);
    }

    @Override
    public int addProxyFailTimes(Long id) {
        // TODO Auto-generated method stub
        return dao.addProxyFailTimes(id);
    }

    public void updateAccountProxyTask() throws Exception {
        List<AccountBean> list = this.dao.getNeedUpdateProxyList(GlobalConfig.query_time_out);
        if (list == null || list.size() == 0) {
            return;
        }
        for (AccountBean account : list) {
            IpPoolBean ipPool = ipPoolService.getOneCanUseIp();
            if (ipPool == null) {
                return;
            }
            AccountBean updateModel = new AccountBean();
            updateModel.setId(account.getId());
            updateModel.setProxy_ip(ipPool.getIp());
            updateModel.setProxy_port(ipPool.getPort());
            updateModel.setProxy_expire_time(ipPool.getExpire_time());
            updateModel.setProxy_fail_times(0);
            this.dao.update(updateModel);
            logger.info("手机号:" + account.getAccount() + ",更新代理IP:(" + ipPool.getIp() + ":" + ipPool.getPort() + ")");
        }
    }

    @Override
    public boolean updateAccountProxy(AccountBean account) throws Exception {
        IpPoolBean ipPool = ipPoolService.getOneCanUseIp();
        if (ipPool == null) {
            throw new Exception("代理IP不足！！！");
        }
        AccountBean updateModel = new AccountBean();
        updateModel.setId(account.getId());
        updateModel.setProxy_ip(ipPool.getIp());
        updateModel.setProxy_port(ipPool.getPort());
        updateModel.setProxy_expire_time(ipPool.getExpire_time());
        updateModel.setProxy_fail_times(0);
        this.dao.update(updateModel);
        account.setProxy_ip(ipPool.getIp());
        account.setProxy_port(ipPool.getPort());
        logger.info("手机号:" + account.getAccount() + ",更新代理IP:(" + ipPool.getIp() + ":" + ipPool.getPort() + ")");
        return true;
    }

    @Override
    public List<AccountBean> getCanDispatchOrderList() {
        // TODO Auto-generated method stub
        return dao.getCanDispatchOrderList();
    }

    @Override
    public int removeAll(String operator) {
        // TODO Auto-generated method stub
        return dao.removeAll(operator);
    }


    @Override
    public int addBuyCount(Long id) {
        // TODO Auto-generated method stub
        return dao.addBuyCount(id);
    }

    @Override
    public void AccountResetStatusTask() {
        // TODO Auto-generated method stub
        dao.resetBindFailCount();//重置绑定次数
        dao.resetBusy();//重置下单繁忙
    }


    @Override
    public int addBindFailCount(Long id) {
        // TODO Auto-generated method stub
        return dao.addBindFailCount(id);
    }

    @Override
    public int resetBindFailCountById(Long id) {
        // TODO Auto-generated method stub
        return dao.resetBindFailCountById(id);
    }

    @Override
    public AccountBean getOneCanQuery(String operator) {
        // TODO Auto-generated method stub
        return dao.getOneCanQuery(operator);
    }

    @Override
    public int batchResetBindFailCount(String operator) {
        // TODO Auto-generated method stub
        return dao.batchResetBindFailCount(operator);
    }

}
